package com.gullmall.ware.service.impl;

import com.gullmall.common.utils.R;
import com.gullmall.ware.entity.PurchaseDetailEntity;
import com.gullmall.common.to.SkuHasStockTo;
import com.gullmall.ware.feign.ProductClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gullmall.common.utils.PageUtils;
import com.gullmall.common.utils.Query;

import com.gullmall.ware.dao.WareSkuDao;
import com.gullmall.ware.entity.WareSkuEntity;
import com.gullmall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
@Transactional
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private ProductClient productClient;

    /**  列表
     * @param params {t=1655323176761, page=1, limit=10, skuId=, wareId=}
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        String skuId=(String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        String wareId=(String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     *  更新/增加 库存 根据skuId和wareId判断是否有记录,有则是更新,没有则是新增
     * @param purchaseDetailEntities 成功的采购项
     */
    @Override
    public R addStock(List<PurchaseDetailEntity> purchaseDetailEntities) {
        for (PurchaseDetailEntity p : purchaseDetailEntities) {
            Long skuId = p.getSkuId();
            Long wareId = p.getWareId();
            WareSkuEntity wareSkuEntity = this.baseMapper.selectOne(new QueryWrapper<WareSkuEntity>()
                    .eq("sku_id", skuId).eq("ware_id", wareId));
            WareSkuEntity insertOrUpdateEntity = new WareSkuEntity();

            if(wareSkuEntity!=null){
                //有记录,更新  update `wms_ware_sku` set stock=stock + ? where id=?
                insertOrUpdateEntity.setId(wareSkuEntity.getId());
                insertOrUpdateEntity.setStock(p.getSkuNum()+wareSkuEntity.getStock());
                this.updateById(insertOrUpdateEntity);
            }else {
                //无记录,新增 insert into `wms_ware_sku`(sku_id,ware_id,stock,sku_name) values(?,?,?,?)
                insertOrUpdateEntity.setStock(p.getSkuNum());
                insertOrUpdateEntity.setSkuId(p.getSkuId());
                insertOrUpdateEntity.setWareId(p.getWareId());
                try {//查不到skuName也不回滚 1,自己catch 2 TODO 高级部分
                    R info = productClient.info(p.getSkuId());
                    if (0==info.getCode()){
                        Map<String,Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                        insertOrUpdateEntity.setSkuName((String) skuInfo.get("skuName"));
                    }
                }catch (Exception e){}

                this.save(insertOrUpdateEntity);
            }
        }
        return R.ok();
    }

    //查询是否有库存
    @Override
    public List<SkuHasStockTo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockTo> skuHasStock = this.getBaseMapper().getSkuHasStock(skuIds);
        List<SkuHasStockTo> collect = skuHasStock.stream().map(m -> {
            if ((m.getReadStock() > 0)) {
                m.setHasStock(true);
            } else {
                m.setHasStock(false);
            }
            return m;
        }).collect(Collectors.toList());
        return collect;
    }


}